
// ==================================================
// 	负责获取数据库的数据并进行整理
// 	20180803
//	刘剑
//	563084506@qq.com
// ==================================================

let millMysql = require("mill-mysql");

module.exports = function (args) {
	var obj = {
	  connectionLimit : 10,
	  host            : 'localhost',
	  user            : 'root',
	  password        : '123',
	  database        : 'test'
	};

	Object.assign(obj,props);//配置对象

	return (new Promise((resolve,reject)=>{
		millMysql.init(obj);
		if(props.tables)
			var condition=props.tables==="*"?"":"AND TABLE_NAME IN ('"+props.tables.split(",").map(i=>i.trim()).join("','")+"')"
		else 
			var condition="";
		let sql = `
		select 
			TABLE_NAME,	
			COLUMN_NAME,
			COLUMN_DEFAULT,	
			IS_NULLABLE,		
			COLUMN_TYPE,	
			DATA_TYPE,
			COLUMN_COMMENT,			
			COLUMN_KEY			
		from information_schema.COLUMNS where TABLE_SCHEMA='${obj.database}' ${condition}`;

		//获取指定数据库的所有表的字段信息
		millMysql.query(sql,[],r=>{
			resolve(r);
			
		});
	})).then(fields=>{
		let sql = `select 
			CONSTRAINT_SCHEMA,
			CONSTRAINT_NAME,
			TABLE_NAME,
			COLUMN_NAME,
			REFERENCED_TABLE_NAME,
			REFERENCED_COLUMN_NAME
		from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where REFERENCED_TABLE_NAME is not null and REFERENCED_TABLE_SCHEMA=?`;

		return new Promise((resolve,reject)=>{

			//获取指定数据库的所有表的字段信息
			millMysql.query(sql,[obj.database],r=>{
				
				let obj = {};
				r.forEach(item=>{//迭代索引表查找外健
					obj[item.TABLE_NAME]||(obj[item.TABLE_NAME]={});
					obj[item.TABLE_NAME][item.COLUMN_NAME]={
						REFERENCED_TABLE_NAME:item.REFERENCED_TABLE_NAME,
						REFERENCED_COLUMN_NAME:item.REFERENCED_COLUMN_NAME,
					}
				});

				//计算这个字段引用了那个表的那个字段
				fields.forEach(field =>{
					try{
						let tm = obj[field.TABLE_NAME][field.COLUMN_NAME];
						
						field.REFERENCED={
							TABLE_NAME:tm.REFERENCED_TABLE_NAME,
							COLUMN_NAME:tm.REFERENCED_COLUMN_NAME
						}
					}catch(e){

					}
					
				});
				
				millMysql.close();

				resolve(fields);

				

			});
		});
		
	});

}





